package com.example.demo.Service;

import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.Entity.Comment;
import com.example.demo.Entity.HistoryVersion;
import com.example.demo.Entity.Note;
import com.example.demo.Entity.User;
import com.example.demo.Mapper.CommentMapper;
import com.example.demo.Mapper.HistoryVersionMapper;
import com.example.demo.Mapper.NoteMapper;
import com.example.demo.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImp implements CommentService {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    HistoryVersionMapper historyVersionMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    NoteMapper noteMapper;

    /**
     * 新增评论
     */
    @Override
    public void insertComment(Comment comment) {
        commentMapper.insert(comment);
    }

    ;

    /**
     * 根据评论ID查询评论
     */
    @Override
    public List<JSONObject> selectById(Integer noteId) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<Comment>()
                .eq("note_id", noteId);
        List<Comment> commentList = commentMapper.selectList(wrapper);

        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        for (Comment comment : commentList) {
            JSONObject result = new JSONObject();
            result.putIfAbsent("text", comment.getText());
            result.putIfAbsent("comm_id", comment.getCommId());
            result.putIfAbsent("time", comment.getTime());
            result.putIfAbsent("like_num", comment.getLikeNum());
            QueryWrapper<User> userWrapper = new QueryWrapper<User>()
                    .eq("id", comment.getUserId());
            User user = userMapper.selectOne(userWrapper);
            result.putIfAbsent("user_id", user.getId());
            result.putIfAbsent("name", user.getName());
            result.putIfAbsent("avatar", user.getAvatar());
            jsonObjectList.add(result);
        }
        return jsonObjectList;
    }

    /**
     * 根据用用户ID查询评论
     */
    @Override
    public List<JSONObject> selectByUserId(Integer userId) {

        QueryWrapper<Note> noteQueryWrapper = new QueryWrapper<Note>()
                .eq("user_id", userId);
        List<Integer> noteIdList = noteMapper.selectList(noteQueryWrapper)
                .stream().map(Note::getNoteId)
                .toList();

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<Comment>()
                .in("note_id", noteIdList);
        List<Comment> commentList = commentMapper.selectList(commentQueryWrapper);

        Set<Integer> idList = commentList.stream()
                .map(Comment::getNoteId).collect(Collectors.toSet());

        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        for (Integer integer : idList) {
            jsonObjectList.addAll(selectById(integer));
        }


        for (JSONObject jsonObject : jsonObjectList) {
            int commId = jsonObject.getShort("comm_id");
            int noteId = commentMapper.findByCommId(commId);
            Note note = noteMapper.selectOne(new QueryWrapper<Note>().eq("note_id", noteId));
            jsonObject.putIfAbsent("note_id", note.getNoteId());
            jsonObject.putIfAbsent("title", note.getTitle());
            jsonObject.putIfAbsent("file", note.getFile());
        }
        
        return jsonObjectList;
    }

    ;

    /**
     * 删除评论
     */
    @Override
    public void deleteById(Integer id) {
        commentMapper.deleteById(id);
    }

    ;

    /**
     * 更新评论
     */
    @Override
    public void update(Comment newComment) {
        commentMapper.insertOrUpdate((newComment));
    }

    ;

    /**
     * 评论点赞
     */
    @Override
    public void upvote(Integer commId) {
        UpdateWrapper<Comment> wrapper = new UpdateWrapper<Comment>()
                .eq("comm_id", commId)
                .setSql("like_num=like_num+1");
        commentMapper.update(wrapper);
    }


    /**
     * 评论取消点赞
     */
    @Override
    public void cancelUpvote(Integer commId) {
        UpdateWrapper<Comment> wrapper = new UpdateWrapper<Comment>()
                .eq("comm_id", commId)
                .setSql( "like_num=like_num-1");
        commentMapper.update(wrapper);
    }


    //得到最新版本信息
    public List<Integer> getNewVersionId(){
        List<HistoryVersion> historyVersionList = historyVersionMapper.selectList(null);
        Map<Integer, Optional<HistoryVersion>> groupedItems = historyVersionList.stream()
                .collect(Collectors
                        .groupingBy(HistoryVersion::getDirectoryId, Collectors
                                .maxBy(Comparator.comparingInt(HistoryVersion::getVersion))));

        List<HistoryVersion> maxHistoryVersion = new ArrayList<>();
        for (Map.Entry<Integer, Optional<HistoryVersion>> entry : groupedItems.entrySet()) {
            if (entry.getValue().isPresent()) {
                maxHistoryVersion.add(entry.getValue().get());
            }
        }
        return maxHistoryVersion.stream()
                .map(HistoryVersion::getNoteId).toList();
    }
    /**
     * 搜集评论数
     */
    @Override
    public List<JSONObject> getCommentNum(Integer userId){
        List<JSONObject> result = new ArrayList<JSONObject>();
        System.out.println(result);
        System.out.println(getNewVersionId());
        for(JSONObject jsonObject : commentMapper.findAllComment()){
            if(getNewVersionId().contains(Integer.parseInt(jsonObject.getStr("note_id")))){
                System.out.println(jsonObject);
                result.add(jsonObject);
            }
        }

        for(JSONObject jsonObject : result){
            int noteId = jsonObject.getShort("note_id");
            String title = noteMapper.selectOne(new QueryWrapper<Note>()
                    .eq("note_id",noteId))
                    .getTitle();
            jsonObject.putIfAbsent("title",title);
        }
        return result;
    }
}
